package com.yunqiao.service.api.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunqiao.common.consts.AppConsts;
import com.yunqiao.common.exception.CustomApiException;
import com.yunqiao.common.pay.AliPay;
import com.yunqiao.common.pay.WxPay;
import com.yunqiao.common.utils.PageUtils;
import com.yunqiao.common.utils.Query;
import com.yunqiao.service.api.UserDepositService;
import com.yunqiao.service.api.entity.OrderCashEntity;
import com.yunqiao.service.api.entity.UserDepositEntity;
import com.yunqiao.service.api.entity.UserEntity;
import com.yunqiao.service.api.mapper.OrderCashMapper;
import com.yunqiao.service.api.mapper.UserDepositMapper;
import com.yunqiao.service.api.mapper.UserMapper;
import com.yunqiao.service.api.vo.UserDepositVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;


@Service("userDepositService")
public class UserDepositServiceImpl extends ServiceImpl<UserDepositMapper, UserDepositEntity> implements UserDepositService {

	@Resource
	private UserDepositMapper userDepositMapper;
	@Resource
	private UserMapper userMapper;
	@Resource
	private OrderCashMapper orderCashMapper;

	@Override
	public PageUtils queryPage(Map<String, Object> params) {
		//各种查询条件的过滤,在此进行
		QueryWrapper queryWrapper = new QueryWrapper<>();
		//状态
		String status = MapUtil.getStr(params, "status");
		if (StrUtil.isNotBlank(status)) {
			queryWrapper.eq("d.status", status);
		}

		String createTime = MapUtil.getStr(params, "createTime");
		String updateTime = MapUtil.getStr(params, "updateTime");
		if (StringUtils.isNotEmpty(createTime) && StringUtils.isNotEmpty(updateTime)) { //当开始时间用
			queryWrapper.between("d.create_time", DateUtil.parse(createTime, "yyyy-MM-dd"), DateUtil.parse(updateTime, "yyyy-MM-dd"));
		}
		IPage<UserDepositVo> iPage = userDepositMapper.getList(new Query<UserDepositVo>(params).getPage(), queryWrapper);
		return new PageUtils(iPage);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public String agent(Long id) throws Exception {
		UserDepositEntity userDepositEntity = userDepositMapper.selectById(id);
		if (!userDepositEntity.getStatus().equals(AppConsts.USER_DEPOSIT_STATUS_1)) {
			throw new CustomApiException("该申请已处理过,请勿重复操作");
		}
		userDepositEntity.setStatus(AppConsts.USER_DEPOSIT_STATUS_2);
		userDepositMapper.updateById(userDepositEntity);

		UserEntity userEntity = userMapper.selectById(userDepositEntity.getUserId());
//		int i = userMapper.updateBalance(userEntity.getId(), userEntity.getBalance().add(userEntity.getDeposit()), userEntity.getBlockBalance(), userEntity.getVersion());
//		if (i == 0) {
//			throw new CustomApiException("请重新确定");
//		}

		List<OrderCashEntity> orderCashEntities = orderCashMapper.selectList(new QueryWrapper<OrderCashEntity>()
				.eq("status", AppConsts.ORDER_CASH_STATUS_2)
				.eq("state", AppConsts.ORDER_CASH_STATE_1)
				.eq("user_id", userEntity.getId())
				.orderByDesc("create_time"));

		if(CollUtil.isEmpty(orderCashEntities)){
			throw new CustomApiException("用户未支付过押金");
		}
		OrderCashEntity orderCashEntity = orderCashEntities.get(0);
		if (orderCashEntity.getType().equals(AppConsts.PAY_TYPE_1)) {
			//支付宝退款
			Boolean flag = AliPay.refund(orderCashEntity.getOrderNumber(), orderCashEntity.getPrice().toString(), RandomUtil.randomNumbers(20), userEntity.getRoleType());
			//支付宝没有回调，直接在这里改变成功状态
			if (!flag) {
				throw new CustomApiException("退款失败");
			}else{
				orderCashEntity.setStatus(AppConsts.ORDER_CASH_STATUS_3);
				orderCashMapper.updateById(orderCashEntity);
				userEntity.setDeposit(new BigDecimal("0"));
				userMapper.updateById(userEntity);
				return "退款成功";
			}
		} else if (orderCashEntity.getType().equals(AppConsts.PAY_TYPE_2)) {
			//微信退款
			String refund = WxPay.refund(orderCashEntity.getOrderNumber(), RandomUtil.randomNumbers(20), orderCashEntity.getPrice().toString(), orderCashEntity.getPrice().toString(), userEntity.getRoleType(),null);
			JSONObject jsonObject = JSONUtil.parseFromXml(refund);
			if (!jsonObject.getStr("return_code").equals("SUCCESS")) {
				throw new CustomApiException("退款失败");
			}else{
				orderCashEntity.setStatus(AppConsts.ORDER_CASH_STATUS_3);
				orderCashMapper.updateById(orderCashEntity);
				userEntity.setDeposit(new BigDecimal("0"));
				userMapper.updateById(userEntity);
				return "退款成功";
			}
		}else {
			return "未找到支付账户,请检查";
		}

	}

	@Override
	public void refuse(UserDepositEntity userDepositEntity) {
		UserDepositEntity userDeposit = userDepositMapper.selectById(userDepositEntity.getId());
		if (!userDeposit.getStatus().equals(AppConsts.USER_DEPOSIT_STATUS_1)) {
			throw new CustomApiException("状态不是申请中");
		}
		userDeposit.setStatus(AppConsts.USER_DEPOSIT_STATUS_3);
		userDeposit.setReason(userDepositEntity.getReason());
		userDepositMapper.updateById(userDeposit);
	}

}
